<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme

export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    unit: {
      type: String,
      default: "kw",
    },
    dataName: {
      type: String,
      default: "容量",
    },
    seriesData: {
      type: Array,
      default: () => []
    },
    totalValue: {
      type: Number,
      default: 0
    }
  },
  watch: {
    seriesData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.updateChart();
        }
      },
      deep: true,
      immediate: true
    },
    totalValue(newVal) {
      if (this.chart) {
        this.updateChart();
      }
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.updateChart();
    },
    updateChart() {
      this.chart.setOption({
        title: {
          show: true,
          text: `{v|${this.totalValue}${this.unit}}\n{t|总${this.dataName}}`,
          x: "center",
          y: "38%",
          textStyle: {
            rich: {
              v: {
                fontSize: 20,
                color: "#fff",
              },
              t: {
                fontSize: 14,
                padding: [10, 0, 0, 0],
                color: "#fff",
              },
            },
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 10,
          bottom: 20,
          textStyle: {
            color: "#ffffff",
          },
          data: this.seriesData.map(item => item.name)
        },
        series: [
          {
            name: this.dataName,
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
              color: '#fff'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold',
                color: '#fff'
              }
            },
            labelLine: {
              show: false,
            },
            data: this.seriesData
          },
        ],
      });
    }
  }
};
</script>